package com.heima.behavior.service.impl;

import com.heima.behavior.dtos.FollowBehaviorDto;
import com.heima.behavior.pojos.ApFollowBehavior;
import com.heima.behavior.service.ApFollowBehaviorService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApTheadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author shitou
 * @className ApFollowBehaviorServiceImpl
 * @description: TODO
 */
@Service
@Slf4j
public class ApFollowBehaviorServiceImpl implements ApFollowBehaviorService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private MongoTemplate mongoTemplate;

    /**
     * 关注用户
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult follow(FollowBehaviorDto dto) {
        log.info("关注用户已经执行");
        // 参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 用户未登录
        ApUser apUser = ApTheadLocalUtil.getApUser();
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 游客需要进行登录，才能进行用户行为
        if (apUser.getId() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        // 用户关注大key
        String userFollowUserId = "USER_FOLLOW_" + apUser.getId();
        // 作者粉丝大key
        String authorFansAuthorId = "AUTHOR_FANS_" + dto.getAuthorId();

        // 用户已关注作者，进行操作  0  关注   重复关注
        boolean followFlag = stringRedisTemplate.opsForHash().hasKey(userFollowUserId, dto.getAuthorId() + "");
        if (followFlag && dto.getOperation() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.USER_FOLLOWED);
        }
        // 用户已关注，进行操作  1  取消
        if (followFlag && dto.getOperation() == 1) {
            // redis 清楚作者的粉丝数，以及当前用户的关注数
            stringRedisTemplate.opsForHash().delete(userFollowUserId, dto.getAuthorId() + "");
            stringRedisTemplate.opsForHash().delete(authorFansAuthorId, apUser.getId() + "");
            // 删除 mongo 中 作者 用户 信息
            Query query = Query.query(Criteria.where("userId").is(apUser.getId()).and("followId").is(dto.getAuthorId()));
            mongoTemplate.remove(query, ApFollowBehavior.class);
        }
        // 用户未关注，进行 关注 行为
        if (!followFlag && dto.getOperation() == 0) {
            // 数据插入mongo
            ApFollowBehavior apFollowBehavior = new ApFollowBehavior();
            apFollowBehavior.setFollowId(dto.getAuthorId());
            apFollowBehavior.setArticleId(dto.getArticleId());
            apFollowBehavior.setCreatedTime(new Date());
            apFollowBehavior.setId(ObjectId.get().toHexString());
            apFollowBehavior.setUserId(apUser.getId().longValue());
            log.info("ObjectId.get().toHexString():{}", ObjectId.get().toHexString());
            mongoTemplate.insert(apFollowBehavior);

            // 插入redis
            stringRedisTemplate.opsForHash().put(userFollowUserId, dto.getAuthorId()+ "", "1");
            stringRedisTemplate.opsForHash().put(authorFansAuthorId,  apUser.getId() + "", "1");
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
